<?php

namespace App\Http\Controllers\api;

use App\Models\BankChargeLog;
use App\Models\Setting;
use Illuminate\Support\Facades\DB;

class SystemController extends BaseController
{
    public function get_account_balance()
    {
        if (!$this->checkAuth()) {
            return $this->error(request()->ip() . ' invalid remote host');
        }
        $bank = Setting::get('bank');

        return $this->success($bank);
    }

    public function set_account_balance()
    {
        if (!$this->checkAuth()) {
            return $this->error(request()->ip() . ' invalid remote host');
        }
        DB::beginTransaction();
        try {
            $bank = Setting::get('bank');
            $attributes = request()->only(['balance', 'lowest_balance']);
            Setting::set('bank', $attributes);
            BankChargeLog::query()->create([
                'ip' => request()->ip(),
                'balance' => $attributes['balance'],
                'before_balance' => $bank['balance'],
                'after_balance' => $attributes['balance'],
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            $this->error($e->getMessage());
        }

        $bank = Setting::get('bank');
        return $this->success($bank);
    }

    public function get_charge_history()
    {
        if (!$this->checkAuth()) {
            return $this->error(request()->ip() . ' invalid remote host');
        }

        $list = BankChargeLog::query()->latest()->get();

        return $this->success($list);
    }

    protected function checkAuth()
    {
        $ip = request()->ip();
        $whitelist = Setting::get('whitelist');
        $whitelist = array_filter(explode(',', $whitelist));
        if (in_array($ip, $whitelist)) {
            return true;
        }

        return false;
    }
}
